<template>
  <div id="addGoods">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 提示 -->
      <el-alert title="添加商品信息" type="info" :closable="false" show-icon center></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="active-0" finish-status="success" align-center :space="200">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab标签栏 -->
      <el-form
        ref="form"
        :rules="addFormRules"
        :model="addForm"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          style="min-height: 200px;"
          v-model="active"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                :options="catelist"
                :props="cateProps"
                v-model="addForm.goods_cat"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item :label="item.attr_name" v-for="(item,index) in manyData"  :key="item.attr_id">
              <el-checkbox-group v-model="checkList[index].attr_vals" @change="a">  <!-- 因为数据和选中存放都放在数组内部的attr_vals里所以需要循环数组的每一项index -->
                <el-checkbox :label="cb" v-for="(cb,index1) in item.attr_vals" :key="index1" border>{{cb}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item :label="item.attr_name" v-for="item in onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              list-type="picture"
              :headers="headerObj"
              :on-success="uploadOnSuccess"
              :on-remove="uploadOnRemove"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <quill-editor
              v-model="addForm.goods_introduce"
            ></quill-editor>
            <el-button type="primary" class="submit" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览上床图片的弹窗 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="30%">
      <img :src="previewPath" style="width:100%" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: "0",
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        // 商品所属的分类数组
        goods_cat: [],
        pics: [],
        // 商品的详情描述
        goods_introduce: "",
        attrs: []
      },
      catelist: [],
      manyData: [],
      onlyData: [],
      checkList: [],
      sign:[0,0],   //标记商品参数sign[0]/属性sign[1]的请求，0表示未请求过，1表示请求过了，若为1，再次进入商品参数/属性标签不用再发起请求
      // 上传图片的URL地址
      uploadURL: "https://www.liulongbin.top:8888/api/private/v1/upload",
      // 预览图片的地址
      previewPath: "",
      //控制预览图片窗口
      dialogVisible: false,
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        expandTrigger: "hover"
      },
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取所有商品分类数据
    getCateList() {
      this.$axios
        .get("categories")
        .then(res => {
          this.catelist = res.data.data;
          console.log(this.catelist);
        })
        .catch(err => {
          return this.$message.error("获取商品分类数据失败！");
        });
    },
    a(a) {
      console.log(a);
      console.log("---",this.checkList)
    },
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
      //初始化进入商品参数/属性的请求次数
      this.sign=[0,0]
    },
    beforeLeave(activeName, oldActiveName) {
      // console.log('即将离开的标签页名字是：' + oldActiveName)
      // console.log('即将进入的标签页名字是：' + activeName)
      // return false
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类！");
        return false;
      }
    },
    tabClick(tab) {
      console.log(tab)
      if (tab.index == 1) {
        if (!this.cateId || this.sign[0]==1) return;
        //获取动态参数
        this.$axios
          .get(`categories/${this.cateId}/attributes`, {
            params: { sel: "many" }
          })
          .then(res => {
            this.manyData = res.data.data;
            this.manyData.forEach(item => {
              item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
              //避免后台的数据是，分割的情况
              if(item.attr_vals.length==1){
                item.attr_vals=item.attr_vals[0].split(",");
              }
            });
              //深拷贝出一个checkList存放勾选的参数，默认是全选（这里的多选框是用manyData渲染的）
              this.checkList=JSON.parse(JSON.stringify(this.manyData));
              //如果没有重新选择分类，再次进去商品参数不会发起请求
              this.sign[0]=1;
          })
          .catch(err => {
            console.log(err);
          });
      } else if (tab.index == 2) {
        if (!this.cateId || this.sign[1]==1) return;
        //获取静态参数
        this.$axios
          .get(`categories/${this.cateId}/attributes`, {
            params: { sel: "only" }
          })
          .then(res => {
            this.onlyData = res.data.data;
            //如果没有重新选择分类，再次进去商品属性不会发起请求
            this.sign[1]=1;
          })
          .catch(err => {
            this.$message.error("获取静态参数列表失败！");
          });
        console.log(this.onlyData);
      }
    },
    //图片预览事件
    handlePreview(file) {
      this.previewPath = file.url;
      this.dialogVisible = true;
    },
    //图片上传成功的钩子
    uploadOnSuccess(res) {
      console.log("上传成功！返回：", res.data.tmp_path);
      this.addForm.pics.push(res.data.tmp_path);
      console.log(this.addForm);
    },
    //移除图片队列的钩子 file:移除的文件信息
    uploadOnRemove(file, fileList) {
      const filePath = file.response.data.tmp_path;
      const i = this.addForm.pics.findIndex(x => x.pic === filePath);
      this.addForm.pics.splice(i, 1);
      console.log(this.addForm);
    },
    //提交按钮
    add(){
      this.$refs.form.validate(valid=>{
        if(!valid){
         return this.$message.error('请填写必要的表单项！')
        }
        //执行添加的业务逻辑
        const form=JSON.parse(JSON.stringify(this.addForm))
        form.goods_cat=form.goods_cat.join(",");
        // 处理动态参数
        this.checkList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          form.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          form.attrs.push(newInfo)
        })
        console.log(form)
        // 发起请求添加商品
        // 商品的名称，必须是唯一的
        this.$axios.post('goods', form).then(res=>{
          console.log(res.data)
          const meta=res.data.meta;
          if(meta.status!=201) return this.$message.error(meta.msg)
          this.$message.success('添加商品成功！')
          this.$router.push('/goods')
        }).catch(err=>{
          console.log(err)
        })
      })
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length == 3) {
        return this.addForm.goods_cat[2];
      } else return null;
    }
  }
};
</script>

<style scoped>
#addGoods >>> .el-steps {
  padding: 20px 0;
}
#addGoods >>> .el-steps .el-step__title {
  font-size: 14px;
}
#addGoods >>> .el-checkbox {
  margin-left: 0;
}
#addGoods >>> .ql-editor{
  min-height: 300px;
}
.submit{
  margin-top: 15px;
}
</style>